package com.jon.experiment3.Service;

import com.jon.experiment3.Dto.RegionStatus;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author 陈伯瑞
 * date 2020/5/7 0007 12:54
 * version 1.0
 **/
@Service
public class covidTrackService implements covidTrackInterface {
    /**
     *covidTrackService
     */
    private  static  final   String CORONA_VIRUS_DATA_URI = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private  List<RegionStatus> regionStatuses = new ArrayList<>();
    /**
     * 【开启定时任务】 计划每天早上八点钟，爬取新的数据 cron = "0 0 8 * * *"
     * @throws IOException IO异常
     * @return
     */
    @Scheduled(cron = "${region.update-cron}")
    public List<RegionStatus> getLastCovidData() throws IOException {
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(CORONA_VIRUS_DATA_URI))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();

        ResponseEntity<Resource> response = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = response.getBody();
        Reader in = new InputStreamReader(body.getInputStream(), "UTF-8");
        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
        boolean isHeader = true;
        String lastDay = "";

        for (CSVRecord record : records) {
            //获取表头
            RegionStatus status = new RegionStatus();
            if (isHeader) {
                isHeader = false;

                String[] split = record.get(record.size() - 1).split("/");
                lastDay = "20" + split[2] + "/" + split[0] + "/" + split[1];
            } else {
                status.setLatestDay(lastDay);
                status.setState(record.get(0));
                status.setCountry(record.get(1));
                status.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
                status.setLatestPreTotalCases(Integer.parseInt(record.get(record.size() - 2)));
                regionStatuses.add(status);
            }

        }
        return regionStatuses;
    }


    public List<RegionStatus> getLastStatesData () {
            return regionStatuses;
        }

    @Override
    public List<RegionStatus> getLastStatesDataByStates(String country) throws IOException {
        List<RegionStatus> result = new ArrayList<>();

        this.regionStatuses.forEach((e) -> {
            if (e.getCountry().toLowerCase().contains(country.toLowerCase())) {
                result.add(e);
            }
        });
        List<RegionStatus> newresult =result.stream().sorted(Comparator.comparing(RegionStatus::getLatestPreTotalCases).reversed()).collect(Collectors.toList());
        return newresult;
    }


}
